package com.lottery.im.module.chat.ui;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.SingleRedPacketsReceived;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.adapter.ChatAdapter;
import com.lottery.im.module.tim.message.CustomMessage;
import com.lottery.im.module.tim.message.Message;
import com.lottery.im.module.tim.message.MessageFactory;
import com.lottery.im.module.tim.model.FriendProfile;
import com.lottery.im.module.tim.model.FriendshipInfo;
import com.lottery.im.module.tim.model.GroupInfo;
import com.lottery.im.module.tim.presenter.ChatPresenter;
import com.lottery.im.module.tim.utils.MediaUtil;
import com.lottery.im.module.tim.viewfeatures.ChatView;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageStatus;
import com.tencent.imsdk.ext.group.TIMGroupSelfInfo;
import com.tencent.imsdk.ext.message.TIMMessageDraft;
import com.tencent.imsdk.ext.message.TIMMessageExt;
import com.tencent.imsdk.ext.message.TIMMessageLocator;
import java.util.ArrayList;
import java.util.List;

/**
 * 查找聊天内容(目前只有群历史记录)
 */
public class ChatRecordSearchFragment extends BaseSwipeFragment implements ChatView {

  public static final String IDENTIFY_KEY = "IDENTIFY_KEY";

  public static ChatRecordSearchFragment create(String identify) {
    ChatRecordSearchFragment fragment = new ChatRecordSearchFragment();
    Bundle b = new Bundle();
    b.putString(IDENTIFY_KEY, identify);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.list) ListView listView;

  private String identify;
  private TIMConversationType type;

  private List<Message> messageList = new ArrayList<>();
  private ChatAdapter adapter;
  private ChatPresenter presenter;
  private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
  private static final int IMAGE_STORE = 200;
  private static final int FILE_CODE = 300;
  private static final int IMAGE_PREVIEW = 400;
  private static final int VIDEO_RECORD = 500;
  private String titleStr;
  private Handler handler = new Handler();
  private boolean isOneLoad = true;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_chat_record_search;
  }

  @Override protected void initPresenter() {
    initView();
  }

  private void initView() {
    identify = getArguments().getString(IDENTIFY_KEY);
    type = TIMConversationType.Group;
    if (null == presenter) {
      presenter = new ChatPresenter(this, identify, type);
    }
    messageList.clear();
    adapter = new ChatAdapter(mActivity, R.layout.item_message, messageList);
    adapter.setOnResendClickListener(postion -> resend(postion));
    listView.setAdapter(adapter);
    listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
    // 滑动顶部 加载更多
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
      private int firstItem;

      @Override
      public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && firstItem == 0) {
          //如果拉到顶端读取更多消息
          presenter.getMessage(messageList.size() > 0 ? messageList.get(0).getMessage() : null);
        }
      }

      @Override
      public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
          int totalItemCount) {
        firstItem = firstVisibleItem;
      }
    });
    switch (type) {
      case C2C:
        if (FriendshipInfo.getInstance().isFriend(identify)) {
          FriendProfile profile = FriendshipInfo.getInstance().getProfile(identify);
          mTvTitle.setText(titleStr = profile == null ? identify : profile.getName());
        } else {
          mTvTitle.setText(titleStr = identify);
        }
        break;
      case Group:
        mTvTitle.setText(GroupInfo.getInstance().getGroupName(identify));
        break;
    }
    presenter.start();
  }

  @OnClick({ R.id.iv_back }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
    }
  }

  /**
   * 显示消息
   */
  @Override public void showMessage(TIMMessage message) {
    if (message == null) {
      adapter.notifyDataSetChanged();
    } else {
      Message mMessage = MessageFactory.getMessage(message);
      if (mMessage != null) {
        if (mMessage instanceof CustomMessage) {
          CustomMessage.Type messageType = ((CustomMessage) mMessage).getType();
          switch (messageType) {
            case TYPING:
              mTvTitle.setText("对方正在输入…");
              handler.removeCallbacks(resetTitle);
              handler.postDelayed(resetTitle, 3000);
              break;
            default:
              break;
          }
        } else {
          if (messageList.size() == 0) {
            mMessage.setHasTime(null);
          } else {
            mMessage.setHasTime(messageList.get(messageList.size() - 1).getMessage());
          }
          messageList.add(mMessage);
          adapter.notifyDataSetChanged();
          listView.setSelection(ListView.FOCUS_DOWN);
        }
      }
    }
  }

  /**
   * 显示消息
   */
  @Override public void showMessage(List<TIMMessage> messages) {
    int newMsgNum = 0;
    for (int i = 0; i < messages.size(); ++i) {
      Message mMessage = MessageFactory.getMessage(messages.get(i));
      if (mMessage == null || messages.get(i).status() == TIMMessageStatus.HasDeleted) continue;
      if (mMessage instanceof CustomMessage && (
          ((CustomMessage) mMessage).getType() == CustomMessage.Type.TYPING ||
              ((CustomMessage) mMessage).getType() == CustomMessage.Type.INVALID)) {
        continue;
      }
      ++newMsgNum;
      if (i != messages.size() - 1) {
        mMessage.setHasTime(messages.get(i + 1));
        messageList.add(0, mMessage);
      } else {
        mMessage.setHasTime(null);
        messageList.add(0, mMessage);
      }
    }
    adapter.notifyDataSetChanged();
    if (isOneLoad) {
      listView.setSelection(ListView.FOCUS_DOWN);
      isOneLoad = false;
    } else {
      listView.setSelection(newMsgNum);
    }
  }

  @Override public void showRevokeMessage(TIMMessageLocator timMessageLocator) {
    for (Message msg : messageList) {
      TIMMessageExt ext = new TIMMessageExt(msg.getMessage());
      if (ext.checkEquals(timMessageLocator)) {
        adapter.notifyDataSetChanged();
      }
    }
  }

  /**
   * 清除所有消息，等待刷新
   */
  @Override
  public void clearAllMessage() {
    messageList.clear();
  }

  /**
   * 发送消息成功
   *
   * @param message 返回的消息
   */
  @Override
  public void onSendMessageSuccess(TIMMessage message) {
    showMessage(message);
  }

  /**
   * 发送消息失败
   *
   * @param code 返回码
   * @param desc 返回描述
   */
  @Override
  public void onSendMessageFail(int code, String desc, TIMMessage message) {
    long id = message.getMsgUniqueId();
    for (Message msg : messageList) {
      if (msg.getMessage().getMsgUniqueId() == id) {
        switch (code) {
          case 80001:
            //发送内容包含敏感词
            msg.setDesc("内容含有敏感词");
            adapter.notifyDataSetChanged();
            break;
          case 10017:
            showToast("因被禁言而不能发送消息");
            break;
        }
      }
    }

    adapter.notifyDataSetChanged();
  }

  /**
   * 发送图片消息
   */
  @Override
  public void sendImage() {}

  /**
   * 发送照片消息
   */
  @Override
  public void sendPhoto() {}

  /**
   * 发送文本消息
   */
  @Override
  public void sendText() {}

  /**
   * 发送文件
   */
  @Override
  public void sendFile() {}

  /*
   *  发送红包
   * */
  @Override public void sendRedPackets() {

  }

  /*
   *  发送名片
   * */
  @Override public void sendBusinessCard() {}

  /*
   * 发送自定义表情
   * */
  @Override public void sendCustonFace(String faceText) {}

  /**
   * 开始发送语音消息
   */
  @Override
  public void startSendVoice() {}

  /*
   * 取消发送提示
   * */
  @Override public void wantToCancel(boolean isWant) {}

  /**
   * 结束发送语音消息
   */
  @Override
  public void endSendVoice(boolean isCancel) {}

  /**
   * 发送小视频消息
   *
   * @param fileName 文件名
   */
  @Override
  public void sendVideo(String fileName) {}

  /**
   * 结束发送语音消息
   */
  @Override
  public void cancelSendVoice() {

  }

  /**
   * 正在发送
   */
  @Override
  public void sending() {}

  /**
   * 显示草稿
   */
  @Override
  public void showDraft(TIMMessageDraft draft) {}

  /**
   * 开启录制小视频
   */
  @Override
  public void videoAction() {}

  /**
   * @param content 群公告弹窗
   */
  @Override public void showGroupNotification(String content) {}

  /**
   * 显示群在线人数情况
   *
   * @param onlineNum 在线人数
   * @param memberNum 总人数
   */
  @Override public void showOnlineNum(int onlineNum, int memberNum) {}

  @Override public void updateGroup(String groupId) {

  }

  @Override public void getSelfGroupProfile(TIMGroupSelfInfo timGroupSelfInfo) {

  }

  @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

  }

  @Override
  public void receiveRedPacketsSuce(SingleRedPacketsReceived singleRedPacketsReceived,String note) {

  }

  /**
   * @param position 重新发送
   */
  private void resend(int position) {}

  /**
   * 将标题设置为对象名称
   */
  private Runnable resetTitle = new Runnable() {
    @Override
    public void run() {
      mTvTitle.setText(titleStr);
    }
  };

  @Override public void onPause() {
    // 强制关闭键盘
    super.onPause();
    presenter.readMessages();
    MediaUtil.getInstance().stop();
  }

  @Override public void onDestroy() {
    super.onDestroy();
    presenter.stop();

  }
}
